import React from 'react';
import { Select } from 'antd';
import { map } from 'lodash';
import FormItem from './formItem';

export default function SearchInput(props) {
    const {
        fd,
        data,
        formItemProps,
        valueProp = 'id',
        nameProp = 'name',
        labelInValue = false,
        notFoundContent = '未找相关数据,请重试',
        placeholder = '请输入查询关键字',
        children,
        onSearch = (v) => v,
        onSelect = (v) => v,
        ...selectProps,
    } = props;
    let timer;
    const handleOnSearch = (inputValue) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            onSearch(inputValue);
        }, 300);
    };
    const {
        filterOption = (inputValue, { props: { data: optionData = {} } = {} }) => {
            const { code, name, nameJp } = optionData;
            return (code && code.indexOf(inputValue) >= 0)
                || (name && name.indexOf(inputValue) >= 0)
                || (nameJp && nameJp.indexOf(inputValue) >= 0);
        },
    } = props;

    const renderOptions = data &&
        map(data, (c) => (
            <Select.Option
                key={`k_${c[valueProp]}`}
                value={`${c[valueProp]}`}
                data={c}
                title={`${c[nameProp]}`}
            >
                {c[nameProp]}
            </Select.Option>)
        );
    const select = (
        <Select
            showSearch
            labelInValue={labelInValue}
            placeholder={placeholder}
            defaultActiveFirstOption
            notFoundContent={notFoundContent}
            filterOption={filterOption}
            onSelect={onSelect}
            onSearch={handleOnSearch}
            {...selectProps}
        >
            {renderOptions || children}
        </Select>
    );
    const selectComp = fd ? fd(select) : select;
    if (formItemProps) {
        return (
            <FormItem
                {...formItemProps}
            >
                {selectComp}
            </FormItem>
        );
    } else {
        return selectComp;
    }
}
